import numpy as np
import pandas as pd
import datetime as dt
import math
from sklearn.svm import SVR
from sklearn.preprocessing import MinMaxScaler
import pickle
import os

# 中值平均值滤波
def MedianAvg_Filter(window_left, window_right, arr):
  size = len(arr)
  result = []
  for i in range(window_left, size-window_right):
    # 滑窗
    temp = []
    for j in range(-window_left, window_right+1):
      temp.append(arr[i+j])
    temp.sort()
    # 可以去掉最大值后，取中位数的平均值
    median_mean = []
    for m in range(1, len(temp)-1):
      median_mean.append(temp[m])

    result.append(np.mean(median_mean))
  return result

def test_cut(train_data, test_data):
    timesteps = 10
    train_data_timesteps = np.array(
        [[j for j in train_data[i:i + timesteps]] for i in range(0, len(train_data) - timesteps + 1)])[:, :, 0]
    test_data_timesteps = np.array(
        [[j for j in test_data[i:i + timesteps]] for i in range(0, len(test_data) - timesteps + 1)])[:, :, 0]
    x_train, y_train = train_data_timesteps[:, :timesteps - 1], train_data_timesteps[:, [timesteps - 1]]
    x_test, y_test = test_data_timesteps[:, :timesteps - 1], test_data_timesteps[:, [timesteps - 1]]
    return x_test, y_test

'''
对外调用接口;
提供给外部其他Python文件调用接口.
'''
def data_process(data,url):
    if url:
        df = pd.read_excel(url)
    else:
        df = data
    df.columns = ['y']
    # 滤波后的数据
    data1 = df[:1000]
    data_filter = np.array(MedianAvg_Filter(10, 10, data1['y'])).reshape(-1, 1)

    # 用前1000轮预测后100轮
    train = pd.DataFrame(data_filter)
    test = df[-100:]
    scaler = MinMaxScaler()
    train_data = scaler.fit_transform(train)
    test_data = scaler.fit_transform(test)
    x_test, y_test = test_cut(train_data,test_data)

    # 当前程序路径问题，进行识别当前路径转换
    curr_url = os.path.join(os.getcwd(),  'SVR_model.pkl')
    # load the saved model
    with open(curr_url, 'rb') as f:
        model = pickle.load(f)

    y_test_pred = scaler.inverse_transform(model.predict(x_test).reshape(-1, 1)).tolist()
    return y_test_pred

if __name__ =="__main__":
    # 读取文件
    url = 'SVR_data.xlsx'
    data = pd.read_excel('SVR_data.xlsx')
    y_test_pred = data_process(data,url)

    # 输出预测值
    print('Predict:', y_test_pred)